﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using HIS.Utils;
using HISModels.Entities;
using System.Configuration;
using Newtonsoft.Json.Linq;
using HISModels.Enums;


namespace HIS.Controllers.FrontOffice
{
    public class Appointment : HIS.Controllers.AppBaseController
    {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private StringReader stringReader = null;
        #endregion

        public Appointment()
        {

        }
        [Authorization(RoleAction = "fo-registration-appoinment")]
        public override void Index()
        {
            //string Lob = Convert.ToString(HttpContext.Current.Session["Lob"]);
            //if (string.IsNullOrEmpty(Lob) && ConfigurationManager.AppSettings["usinglob"] == "true") {
            //    //flag
            //    string url = Data["rooturl"] + "frontoffice/lobselection/?redirectUri=patientdata/default";
            //    HttpContext.Current.Response.Redirect(url);
            //}
            try
            {
                Data.Add("Pagetitle", "Appointment");
                Data.Add("Actionform", Data["rooturl"] + "opd/fo/Appointment");
                //Data.Add("Notification", strNotification);

                string ddlSpecialist = DropDownSpecialist("");
                Data.Add("ddlSpecialists", ddlSpecialist);

                //string ddlDoctor = DropDownDoctor("");
                //Data.Add("ddlDoctors",ddlDoctor);

                string ddlHospitals = DropDownHospital("");
                Data.Add("ddlHospitals", ddlHospitals);


                RenderFile("frontoffice\\appointmentsearch.html");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }



         [Authorization(RoleAction = "fo-registration-appoinment")]
        public void GetJson()
        {
            int paramDoctorId = Convert.ToInt32(HttpContext.Current.Request["doctorid"]);
            //from fullcalendar
            int startD = Convert.ToInt32(HttpContext.Current.Request["start"]);
            int endD = Convert.ToInt32(HttpContext.Current.Request["end"]);

            DateTime startdatebycallendar = GetDateTimeFromFullCalendar(startD);
            DateTime enddatebycallendar = GetDateTimeFromFullCalendar(endD).AddDays(1);

            string param = string.Format("doctorid={0};startdate={1};enddate={2}", paramDoctorId, startdatebycallendar.ToString(StaticVariables.DateFormat), enddatebycallendar.ToString(StaticVariables.DateFormat));


            DoctorSchedule dt = new DoctorSchedule();

            string strUri = Global.ServiceUriDictionary["appschedule"] + Global.ServiceUriDictionary["requestformat"];
            StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(param));



            string strJson = stringReader.ReadToEnd();
            List<DoctorSchedule> dc = JsonConvert.DeserializeObject<List<DoctorSchedule>>(strJson);

            stringReader.Dispose();
            base.RestService.Dispose();

            List<test> oo = new List<test>();

            DateTime tempDt = startdatebycallendar;

         
        
            while (tempDt <= enddatebycallendar)
            {

                foreach (var o in dc)
                {
                    if (Convert.ToInt32(tempDt.Date.DayOfWeek) == Convert.ToInt32(o.DaySet))
                    {
                        test x = new test();
                        TimeSpan scStart = (TimeSpan)o.StartScheduleTime;
                        TimeSpan scEnd = (TimeSpan)o.EndScheduleTime;

                        x.title = scStart.ToString( @"h\:m") + " - " + scEnd.ToString(@"h\:m");
                        x.start = tempDt.Date.ToString("yyyy-MM-dd");
                        x.end = tempDt.Date.ToString("yyyy-MM-dd");
                        x.url = "";
                        x.allDay = true;
                        x.color = "yellow";
                        x.textColor = "black";

                        oo.Add(x);

                    }
                }
                tempDt = tempDt.AddDays(1);
            }



            foreach (var o in dc)
            {
                foreach (var ap in o.Appointments)
                {
                    test x = new test();
                    x.id = ap.Id.ToString();
                    x.title = ap.BookerName;
                    x.start = Convert.ToDateTime(ap.StartTime).ToString("yyyy-MM-dd HH:mm");
                    x.end = Convert.ToDateTime(ap.EndTime).ToString("yyyy-MM-dd HH:mm");
                    x.url = "";
                    x.allDay = false;

                    if (ap.IsInRange == 0)
                    {
                        x.color = "pink";
                        x.textColor = "black";
                    }

                    oo.Add(x);
                }
            }

          


            string y = JsonConvert.SerializeObject(oo);

            HttpContext.Current.Response.Write(y);


        }

        private DateTime GetDateTimeFromFullCalendar(int TimeStamp)
        {
            DateTime dt = new DateTime(1970, 1, 1);
            dt = dt.AddSeconds(TimeStamp);
            return dt;

        }
        public string DropDownHospital(string Selected)
        {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            strUri = Global.ServiceUriDictionary["hospital"] + Global.ServiceUriDictionary["requestformat"];
            try
            {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.RefHu> listSp = JsonConvert.DeserializeObject<List<RefHu>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                activeArr.Add(new object[] { 0, Name = "- All Hospitals -" });
                //activeArr.Add(new object[] { 1, Name = "Siloam Karawaci" });
                //activeArr.Add(new object[] { 2, Name = "Siloam Bonjer" });


                foreach (RefHu item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("IdHospital", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            }
            catch
            {
            }
            finally
            {
                // stringReaderDropDown.Dispose();
            }
            return strResult;
        }
        public string DropDownSpecialist(string Selected)
        {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";

            strUri = Global.ServiceUriDictionary["doctorspecialist"] + Global.ServiceUriDictionary["requestformat"];
            try
            {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<RefSpecialist> listSp = JsonConvert.DeserializeObject<List<RefSpecialist>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                activeArr.Add(new object[] { 0, Name = "- All Specialist -" });


                foreach (RefSpecialist item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("IdSpecialist", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            }
            catch
            {
            }
            finally
            {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        [Authorization(RoleAction = "fo-registration-appoinment")]
        public void TableList()
        {
            try
            {

                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];

                string hospitalid = HttpContext.Current.Request["IdHospital"].NullSafeToString();
                string specialistid = HttpContext.Current.Request["IdSpecialist"].NullSafeToString();
                string doctorname = HttpContext.Current.Request["TextBoxDoctorName"].NullSafeToString();

                string ssearch = "hospitalid=" + hospitalid + ";specialistid=" + specialistid + ";doctorname=" + doctorname;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = "";
                strUri = Global.ServiceUriDictionary["appschedulepaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));


                strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();


                HttpContext.Current.Response.Write(strJson);

                //tanto mock

                // HttpContext.Current.Response.Write(MockData());


            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

     
        [Authorization(RoleAction = "fo-registration-appoinment")]
        public void DoctorsScheduleSelected()
        {
            int doctorId = Convert.ToInt32(HttpContext.Current.Request["doctorid"]);


            string strUrl = Global.ServiceUriDictionary["doctor"] + doctorId + Global.ServiceUriDictionary["requestformat"];

            //stringReader = base.RestService.GetJson(strUrl);
            //string temp = stringReader.ReadToEnd();

            stringReader = base.RestService.GetJson(strUrl);
            string xx = stringReader.ReadToEnd();
            var obj = JsonConvert.DeserializeObject<ViewDataDoctor>(xx);

            //JObject o = JObject.Parse(xx);
            //JArray aaData = (JArray)o["Detail"];

            //JArray aaDataModified = new JArray();
            //for (int i = 0; i < aaData.Count(); i++)
            //{
           // var oo = aaData[0];
            // JObject oo = JObject.Parse(aaData[i].ToString());
            Data.Add("DoctorName",  obj.FullName);
            Data.Add("Specialist",obj.SubSpecialist);
            Data.Add("DoctorId", obj.DoctorId);

            //DoctorName = (oo["doctorname"]).ToString();
            //GroupSpecialist = (oo["grupspecialist"]).ToString();
            //SubSpecialist = (oo["subspecialist"]).ToString();
            //aaDataModified.Add(oo);

            //}



            //d.Id = doctorId;
            //d.FirstName = "Dwi";
            //d.LastName = "Tanto";


            Data.Add("Pagetitle", "Appointment");
            Data.Add("Doctor", new Doctor());

            Data.Add("Actionform", "#");
            //Data.Add("Notification", strNotification);
            RenderFile("frontoffice\\appointmentindex.html");







        }

        private void GetDateRange(out DateTime startDate, out DateTime endDate)
        {
            var now = DateTime.Now.Date;
            startDate = now.AddDays(-1 * ((int)(now.DayOfWeek) - 1));
            endDate = startDate.AddDays(7);

        }


        [Authorization(RoleAction = "fo-registration-appoinment")]
        public void ProsessAjax()
        {
            try
            {
                var stream = HttpContext.Current.Request.InputStream;
                StreamReader sr = new StreamReader(stream);
                string s = sr.ReadToEnd();
                test x = JsonConvert.DeserializeObject<test>(s);

                var start = Convert.ToDateTime(x.start);
                var end = Convert.ToDateTime(x.end);
                var title = x.title;
                var phone = x.phone;
                var patientid = x.patientid;


                //save to server

                if (x.id.Equals("0")) // add appointment
                {

                    string strUrl = Global.ServiceUriDictionary["appointment"] + Global.ServiceUriDictionary["requestformat"];
                    // var data = HttpContext.Current.Request;
                    string param = "id=" + x.doctorid + ";start=" + start.ToString(HISModels.Enums.StaticVariables.DateTimeFormat) + ";end=" + end.ToString(HISModels.Enums.StaticVariables.DateTimeFormat) + ";title=" + title + ";phone=" + phone + ";patientid=" + patientid;
                    stringReader = base.RestService.PostJson(strUrl, JsonConvert.SerializeObject(param));
                    string dt = stringReader.ReadToEnd();
                   
                }
                else
                {

                    string strUrl = Global.ServiceUriDictionary["appointment"] + Global.ServiceUriDictionary["requestformat"];
                    // var data = HttpContext.Current.Request;
                    string param = "id=" + x.id + ";title=" + title + ";phone=" + phone + ";patientid=" + patientid;
                    stringReader = base.RestService.PutJson(strUrl, JsonConvert.SerializeObject(param));
                    string dt = stringReader.ReadToEnd();
                   

                }

                string result = "";
                HttpContext.Current.Response.Write(JsonConvert.SerializeObject(result));
            }
            catch (Exception ex)
            {

                HttpContext.Current.Response.Write(JsonConvert.SerializeObject(ex.Message));
            }
        }
        [Authorization(RoleAction = "fo-registration-appoinment")]
        public void DeleteAjax()
        {
            try
            {
                string temp = HttpContext.Current.Request["id"];
                string strUrl = Global.ServiceUriDictionary["appointment"] + Global.ServiceUriDictionary["requestformat"];
                int param = Convert.ToInt32(temp);
                stringReader = base.RestService.DeleteJson(strUrl, JsonConvert.SerializeObject(param));
                string dt = stringReader.ReadToEnd();
                var oo = JsonConvert.DeserializeObject<HISModels.Entities.Appointment>(dt);
                HttpContext.Current.Response.Write(oo.Id);
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }


        }
        public void PopUpAppointment()
        {
            try
            {
                RenderFile("FrontOffice\\appointmentpopupadd.html");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
        [Authorization(RoleAction = "fo-registration-appoinment")]
        public void SearchAppointment()
        {
            string key = HttpContext.Current.Request["id"];
          
            HISModels.Entities.Appointment dt = new  HISModels.Entities.Appointment();

            string strUri = Global.ServiceUriDictionary["appointment"] + key + Global.ServiceUriDictionary["requestformat"];
            StringReader stringReader = base.RestService.GetJson(strUri);

            string result = stringReader.ReadToEnd();
            
            dt = JsonConvert.DeserializeObject< HISModels.Entities.Appointment>(result);

            var rtrnData = new { phone = dt.PhoneNumber, patientid=dt.PatientId, title =dt.BookerName };
            var trn = JsonConvert.SerializeObject(rtrnData);
            HttpContext.Current.Response.Write(trn);



            
        }
        [Authorization(RoleAction = "fo-registration-appoinment")]
        public void SearchPatient()
        {

            string key = HttpContext.Current.Request["name"];
            


            string param = string.Format("name={0}", key);


            Patient dt = new Patient();

            string strUri = Global.ServiceUriDictionary["patientbyname"] + Global.ServiceUriDictionary["requestformat"];
            StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(param));


           




            string strJson = stringReader.ReadToEnd();
            List<Patient> dc = JsonConvert.DeserializeObject<List<Patient>>(strJson);

            List<object> data = new List<object>();

            foreach (Patient p in dc)
            {
                string val = (p.FirstName + " " + p.MiddleName + " " + p.LastName).Trim();

                string lbl = (p.FirstName + " " + p.MiddleName + " " + p.LastName).Trim();

                var x = new { label = lbl, value = val, id = p.Id, phone = p.PhoneNumber };
                data.Add(x);
            }
           // string strJson = JsonConvert.SerializeObject(lp);
            string strResult = JsonConvert.SerializeObject(data);
            HttpContext.Current.Response.Write(strResult);

           
        }
        [Authorization(RoleAction = "fo-registration-appoinment")]
        public void IsItExistSchedule()
        {
            string doctorId = HttpContext.Current.Request["doctorId"];
            string dayOfWeek = HttpContext.Current.Request["dayOfWeek"];

            System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;


            var start = DateTime.ParseExact(HttpContext.Current.Request["startDt"], "yyyy-MM-dd HH:mm", provider);

           

            string param = string.Format("doctorId={0};dayOfWeek={1}", doctorId, dayOfWeek);

      

            string strUri = Global.ServiceUriDictionary["doctorschedcheck"] + Global.ServiceUriDictionary["requestformat"];
            StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(param));

            bool temp1 = Convert.ToBoolean(stringReader.ReadToEnd());


           

           bool temp2 = start < DateTime.Now ? false : true;

           bool result = temp1 && temp2;



            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(result));
        }

    }
    public class test
    {
        public string id { get; set; }
        public string doctorid { get; set; }
        public string title { get; set; }
        public string start { get; set; }
        public string end { get; set; }
        public string url { get; set; }
        public bool allDay { get; set; }
        public string color { get; set; }
        public string textColor { get; set; }
        public string phone { get; set; }
        public string patientid { get; set; }
    }
}